<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/4/13
 * Time: 上午11:11
 *
 * 功能：系统定时维护过期的优惠券配置，标识状态为过期状态
 * 版本：v1.0
 *
 *
 * 规则：一分钟一次
 *
 */

ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\activity\CouponConfig as mCouponConfig;
use Biz\service\activity\Coupon as sCoupon;
use Biz\module\Classes\Coupon as clsCoupon;

if (isset($argv[1])) {
    $stopMiunte = date('Y-m-d H:i:00', strtotime($argv[1]));
} else {
    $stopMiunte = date('Y-m-d H:i:00', time());
}


$where = [
    'OR'     => [
        'AND #1' => [
            'type_time'    => mCouponConfig::TYPE_TIME_STATIC,
			'stop_time[<]' => $stopMiunte,
        ],
        'AND #3' => [
            'received_count[>=]' => \Medoo\Medoo::raw('total_count')
        ],
        'AND #2' => [
            'type_time' => mCouponConfig::TYPE_TIME_RELATIVELY,
        ],
    ],
    'status' => [mCouponConfig::STATUS_CAN_RECEIVE],
];

try {
    //取出待处理的数据
    $couponConfigList = mCouponConfig::select("*", $where);

    if (empty($couponConfigList)) {
        throw new \Exception("当前时刻没有待处理的优惠券数据");
    }

    foreach ($couponConfigList as $couponConfig) {

        try {

            if($couponConfig['type_time'] == mCouponConfig::TYPE_TIME_STATIC){
                clsCoupon::setCouponCannotReceive($couponConfig['coupon_id'],['status' => mCouponConfig::STATUS_CAN_RECEIVE, 'OR' => ['stop_time[<]' => $stopMiunte , 'stop_show_time[<]' => $stopMiunte]]);
            }

            clsCoupon::setCouponCannotReceive($couponConfig['coupon_id'],['status' => mCouponConfig::STATUS_CAN_RECEIVE,'received_count[>=]'=>\Medoo\Medoo::raw('total_count')],clsCoupon::REASON_1);

            sCoupon::admCacheCouponConfig($couponConfig['coupon_id']);

        } catch (\Exception $e) {

            echo sprintf("%s    时刻:%s   coupon_id:%s   异常：%s  \n", date('Y-m-d H:i:s'), $stopMiunte, $couponConfig['coupon_id'], json_encode([
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine(),
                'e_msg'  => $e->getMessage()
            ], JSON_UNESCAPED_UNICODE));

        } finally {
            \Doraemon\tools\Log::info('coupon_id:'.$couponConfig['coupon_id'], mCouponConfig::sqlLogs());

            mCouponConfig::clearLogs();
        }
    }
} catch (\Exception $e) {

    \Doraemon\tools\Log::error('message:'.$e->getMessage(), mCouponConfig::sqlLogs());

    mCouponConfig::clearLogs();


}






